package com.gang.music.core.shiro;

import com.gang.music.system.entity.User;
import com.gang.music.system.service.UserService;
import com.smallchill.core.toolbox.kit.DateTimeKit;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Calendar;
import java.util.Date;

/**
 * 记录用户密码错误次数
 *
 */
public class RetryLimitHashedCredentialsMatcher extends
		HashedCredentialsMatcher {
	
	/**
	 * 运行密码错误的次数
	 */
	private static final int PASSERRORCOUNT = 5;
	
	/**
	 * 密码锁定分钟数
	 */
	private static final int PASSERRORMIN = 10;
	
	@Autowired
	private UserService userService;
	
	@Override
	public boolean doCredentialsMatch(AuthenticationToken token,
			AuthenticationInfo info) {
		ShiroUser shirouser = (ShiroUser) info.getPrincipals().getPrimaryPrincipal();
		
		User user = userService.selectById(shirouser.getId());
		
		boolean matches = super.doCredentialsMatch(token, info);
		//如果密码正确则将passErrorCount置为0,isLock置为true
		if (matches) {
			user.recovery();
		}else {
			user.setPassErrorCount(user.getPassErrorCount() + 1);
			if(user.getPassErrorCount() >= PASSERRORCOUNT) {
				user.setLock(true);
				Date unlockTime = 
						DateTimeKit.offsiteDate(new Date(), Calendar.MINUTE, PASSERRORMIN);
				user.setUnlockTime(unlockTime);
			}
		}
		userService.updateById(user);
		if(user.getLock()) 
			throw new ExcessiveAttemptsException(DateTimeKit.formatDateTime(user.getUnlockTime()));
		return matches;
	}
}
